package cn.zebra.dev.oss.module.tencent.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.common.utils.NumberUtils;
import cn.zebra.dev.oss.module.base.service.BaseOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.zebra.dev.common.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

/**
 * @author runnable@sina.cn
 */
@Api(tags = "文件上传服务")
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private BaseOssService ossService;

    @PostMapping("/uploadFile")
    @ApiOperation("文件上传")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }
        //上传文件
        String filename = file.getOriginalFilename();
        if (StrUtils.isBlank(filename)) {
            return Result.error("文件名不能为空!");
        }
        String suffix = filename.substring(filename.lastIndexOf("."));
        String url = ossService.uploadSuffix(file.getBytes(), suffix);
        return Result.success(url);
    }

    @PostMapping("/uploadImg")
    @ApiOperation("文件图片")
    public Result uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        String filename = file.getOriginalFilename();
        if (StrUtils.isBlank(filename)) {
            return Result.error("文件名不能为空!");
        }
        InputStream inputStream = file.getInputStream();
        int available = inputStream.available();
        BigDecimal byteSize = new BigDecimal(available);
        BigDecimal mbSize = NumberUtils.div(byteSize, new BigDecimal(1024 * 1024));
        if (mbSize.compareTo(new BigDecimal(15)) > 0) {
            return Result.error("文件请勿超过15MB!");
        }
        String suffix = filename.substring(filename.lastIndexOf("."));
        String url = ossService.uploadSuffix(file.getBytes(), suffix);
        return Result.success(url);
    }
}
